<template>
    <el-form ref="nameFormRef" :model="form" :rules="rules" label-width="55px">
        <el-row :gutter="20">
            <el-col :span="5" :xs="24">
                <el-row>
                    <el-col>
                        <el-form-item  prop="avatar" label-width="0">
                            <UserAvatar v-model="form.avatar" :src="uploadSrc.NAME_AVATAR" :url = "form.avatarUrl" :fileName="fileName"></UserAvatar>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="性别" prop="gender" label-width="40px">
                            <el-select v-model="form.gender" placeholder="性别" clearable>
                                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="19" :xs="24">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="姓氏" prop="name">
                            <el-input v-model="form.name" placeholder="钱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="名" prop="lastName">
                            <el-input v-model="form.lastName" placeholder="请输入谱名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="常用名" prop="commonName">
                            <el-input v-model="form.commonName" placeholder="请输入常用名" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="别名" prop="alias">
                            <el-input v-model="form.alias" placeholder="请输入别名" />
                        </el-form-item>
                    </el-col> -->
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="父母" prop="parentName">
                            <el-input v-model="form.parentName" placeholder="父母"  disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关系" prop="relation">
                            <el-select v-model="form.relation" placeholder="关系" >
                                        <el-option
                                        v-for="dict in relation"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                        ></el-option>
                                    </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="排行" prop="rankNo">
                            <el-select v-model="form.rankNo" placeholder="排行">
                                <el-option
                                v-for="dict in rank"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学校" prop="school">
                            <el-input v-model="form.school" placeholder="学校名称" >
                                <template #append>
                                    <el-input v-model="form.professional" placeholder="就读专业名称" class="professAppend"/>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学历" prop="degree">
                            <el-select v-model="form.degree" placeholder="请选择学历">
                                <el-option
                                v-for="dict in degree"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item  prop="degreeStatus" label-width="0px">
                            <el-select v-model="form.degreeStatus" style="width: 80px">
                                <el-option
                                v-for="dict in education_status"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="职务" prop="duties">
                            <el-input v-model="form.duties" placeholder="请输入职务" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="头衔" prop="title">
                            <el-input v-model="form.title" placeholder="请输入头衔" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    
                    <el-col :span="12">
                        <el-form-item label="生于" prop="birthday">
                            <el-date-picker
                                v-model="form.birthday"
                                type="date"
                                placeholder="出生日期"
                                size="default"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item  prop="status" label="状态">
                            <el-select v-model="form.status">
                                <el-option
                                v-for="dict in person_status"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20" v-if="form.status=='1'">
                    <el-col :span="12">
                        <el-form-item label="逝于" prop="deadTime">
                            <el-date-picker
                                v-model="form.deadTime"
                                type="date"
                                placeholder="去世日期"
                                size="default"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="葬地" prop="burialSite">
                            <el-input v-model="form.burialSite" placeholder="葬地" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="住址" prop="desc">
                            <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="说明" prop="desc">
                            <el-input v-model="form.mark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <div>
                    <div class="inline-select-wrapper">
                        <span class="label-text">子女信息：</span>
                        <el-button @click="insertEvent" class="addChildBtn"><el-icon><Plus /></el-icon>增加子女</el-button>
                        <span class="label-text">共</span>
                        <el-select class="inline-select" placeholder="" v-model="sonNum">
                            <el-option
                            v-for="dict in child_num"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                            ></el-option>
                        </el-select>
                        <span class="label-text">子</span>
                        <el-select class="inline-select" placeholder="" v-model="daughterNum">
                            <el-option
                            v-for="dict in child_num"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                            ></el-option>
                        </el-select>
                        <span class="label-text">女</span>
                    </div>
                    <vxe-table
                    border
                    show-overflow="title"
                    :merge-cells=mergeCells
                    keep-source
                    ref="tableRef"
                    :edit-config="{ trigger: 'click', mode: 'row', showStatus: true}"
                    :data="tableData">
                    <vxe-column title="姓"   field ="name" width="80"></vxe-column>
                    <vxe-column title="名字" field="lastName" width="150" :edit-render="{name:'ElInput'}"></vxe-column>
                    <vxe-column title="性别" field="gender" width="120" :edit-render="sexEditRender"></vxe-column>
                    <vxe-column title="父母" field="parentName" min-width="120" ></vxe-column>
                    <vxe-column title="关系" field="relation" width="120"  :edit-render="relEditRender"></vxe-column>
                    <vxe-column title="排行" field="rankNo" width="100" :edit-render="rankEditRender"></vxe-column>
                    </vxe-table>
                </div>
            </el-col>
        </el-row>
    </el-form>
</template>
<script setup lang="ts">
    import UserAvatar from '@/views/system/user/profile/userAvatar.vue';
    import { NameVO, NameQuery, NameForm } from '@/api/genealogy/name/types';
    import type { VxeTableInstance, VxeColumnPropTypes,VxeTablePropTypes } from 'vxe-table'

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { degree, rank, relation,sys_user_sex,education_status,person_status,child_num } = toRefs<any>(proxy?.useDict('degree', 'rank', 'relation','sys_user_sex','education_status','person_status','child_num'));

    const parentNames = ref(null);
    const nameFormRef = ref<ElFormInstance>();
    const sonNum =ref('0');
    const daughterNum =ref('0');
    const rowspans = ref(0);
    const fileName = 'file'

    const uploadSrc = {
        /** 族员头像上传地址 */
        NAME_AVATAR: `${import.meta.env.VITE_APP_BASE_URL}/genealogy/name/avatar`,
    }


    const initFormData: NameForm = {
        id: undefined,
        geneName: undefined,
        name: undefined,
        lastName: undefined,
        commonName: undefined,
        alias: undefined,
        mark: undefined,
        parentId: undefined,
        relation: undefined,
        parentName: undefined,
        rankNo: undefined,
        school: undefined,
        professional: undefined,
        degree: 'none',
        gender: '0',
        duties: undefined,
        title: undefined,
        birthday: undefined,
        status: '0',
        deadTime: undefined,
        burialSite: undefined,
        personType: undefined,
        otherId: undefined,
        geId: undefined,
        degreeStatus:'0',
        address:undefined,
        avatar:undefined,
        avatarUrl:undefined,
        childrenList:[],
        wifeList:[]
    }

    interface DictData {
        sexData:DictDataOption[],
        relData:DictDataOption[],
        ranData:DictDataOption[]
    }

    const dict = ref<DictData>({
        sexData:sys_user_sex.value,
        relData:relation.value,
        ranData:rank.value
    })

    const data = reactive<PageData<NameForm, NameQuery>>({
        form: {...initFormData},
        queryParams: {
            geneName: undefined,
        },
        rules: {
            
        }
    });

    const { queryParams, form, rules } = toRefs(data);

    /**可编辑表格相关 */
    const tableData = ref<NameForm[]>([])

    const tableRef = ref<VxeTableInstance<NameForm>>()
    const mergeCells = ref<VxeTablePropTypes.MergeCells>([
        { row: 0, col: 0, rowspan: rowspans.value, colspan: 1 },
    ])

    let sexRef = ref([]);
    let relRef = ref([]);
    let rankRef = ref([]);

        /**监听事件相关 */
    watch([sys_user_sex,relation,rank],([newSex,newRel,newRank],[oldSex,oldRel,oldRank]) =>{
        dict.value =<DictData> {
            sexData:newSex,
            relData:newRel,
            ranData:newRank
        }
        loadDict();
    })

    
    /**可编辑框性别渲染 */
    const sexEditRender = reactive<VxeColumnPropTypes.EditRender>({
        name: 'ElSelect',
        options: sexRef.value
    })

    const relEditRender = reactive<VxeColumnPropTypes.EditRender>({
        name: 'ElSelect',
        options: relRef.value
    })

    const rankEditRender = reactive<VxeColumnPropTypes.EditRender>({
        name: 'ElSelect',
        options:rankRef.value
    })

    //点击姓名渲染表单数据
    const loadForm = (data) =>{
        nameFormRef.value.resetFields();
        Object.assign(form.value, data);
        tableRef.value.reloadData(data.childrenList);
        sonNum.value = ''+data.sonNum;
        rowspans.value = data.childrenList.length
        daughterNum.value = ''+data.daughterNum;
    }

    const insertEvent = async () => {
        const $table = tableRef.value
        if ($table) {
            const record = {
                parentName: form.value.name+form.value.lastName,
            }
            const { row: newRow } = await $table.insert(record)
            $table.setEditRow(newRow)
            rowspans.value++
        }
    }

    /** 提交按钮 */
    const getFatherFormData = async  () => {
        return new Promise((resolve) => {
            nameFormRef.value?.validate((valid: boolean) => {
                if (valid) {
                    // 验证通过，返回表单数据
                    console.log("子表数据",tableRef.value.getFullData())
                    form.value.childrenList = tableRef.value.getFullData()
                    resolve(form.value);
                } else {
                    // 验证失败，返回 null 或其他标识
                    resolve(null);
                }
            });
        })
    }

    const loadDict = ()=>{
        if(dict.value.sexData.length != 0&&sexRef.value.length==0){
            dict.value.sexData.forEach(sexObj => {
                sexRef.value.push({label:sexObj.label,value:sexObj.value}) 
            });
        }
        if(dict.value.relData.length != 0&&relRef.value.length==0){
            dict.value.relData.forEach(obj => {
                relRef.value.push({label:obj.label,value:obj.value}) 
            });
        }
        if(dict.value.ranData.length != 0&&rankRef.value.length==0){
            dict.value.ranData.forEach(obj => {
                rankRef.value.push({label:obj.label,value:obj.value}) 
            });
        }
    }

    /**抛出方法供父组件调用 */
    defineExpose({
        loadForm,
        getFatherFormData,
        loadDict
    });
    
</script>
<style scoped>
    .img-lg{
        width: 80px;
        height: 80px;
    }
    .user-info-head{
        height: 80px !important;
    }
    /**子表文字和下拉框布局 */
    .inline-select-wrapper{
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
    }
    .inline-select{
        width: 80px;
    }
    .addChildBtn{
        background-color: var(--el-button-hover-bg-color);
        border-color: var(--el-button-hover-border-color);
        color: var(--el-button-hover-text-color);
        outline: none;
    }
</style>